package com.atguign.gulimall.order.listener;

import com.atguign.gulimall.order.config.MqConfig;
import com.atguign.gulimall.order.entity.OrderEntity;
import com.atguign.gulimall.order.enume.OrderStatusEnum;
import com.atguign.gulimall.order.service.OrderService;
import com.atguigu.common.to.mq.OrderTo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {
    @Autowired
    OrderService orderService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 监听过期订单
     * @param orderEntity
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    @Transactional
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        log.debug("收到过期订单：{}",orderEntity);
        try{
            closeOrder(orderEntity);
        }catch (RuntimeException e){
            log.error("订单关闭失败{}",e.toString());
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 订单超时取消订单
     * @param orderEntity
     */
    @Transactional
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity byId = orderService.getById(orderEntity.getId());
        //待付款需要取消订单
        if(Objects.equals(byId.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())){
            boolean update = orderService.update(new LambdaUpdateWrapper<OrderEntity>().set(OrderEntity::getStatus, OrderStatusEnum.CANCLED.getCode()).eq(OrderEntity::getId, orderEntity.getId()));
            if(update){
                log.debug("订单关闭成功 {}",orderEntity.getId());
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(byId, orderTo);
                //TODO 发送消息给库存解锁库存
                rabbitTemplate.convertAndSend(MqConfig.ORDER_EVENT_EXCHANGE, "order.release.other", orderTo);
            }else{
                log.error("订单关闭失败");
                throw new RuntimeException("订单关闭失败");
            }
        }
    }
}
